
import React, { useEffect, useState } from 'react';
import SectionTitle from '@/components/SectionTitle'
import InitForm from '@/components/InitForm';
import { Image, Empty, Card, Button, Input, Checkbox, Tooltip, Form, message, Popconfirm } from 'antd';
import styles from "./index.less"
import DragModal from '@/components/DragModal'
import ProList from '@ant-design/pro-list';
import { SearchOutlined, EyeFilled, ClockCircleFilled } from '@ant-design/icons'
import { doFetch } from '@/utils/doFetch'
import { useRequest } from 'umi'
import Avatar from 'antd/lib/avatar/avatar';
import { useMemo } from 'react';
import moment from 'moment';
import defaultFields from './fields';

function unique(arr) {
    var hash = [];
    for (var i = 0; i < arr.length; i++) {
        let hashlist = hash.length > 0 ? hash : [];
        if (arr[i] && hashlist.indexOf(arr[i]) == -1) {
            hash.push(arr[i]);
        }
    }
    return hash;
}
function formartData(item, val) {
    let formartValue = val;
    if (item.type == 'upload') {
        let stepval = val ? (Array.isArray(val) ? val : val.fileList) : [];
        formartValue = stepval.map((it) => {
            if (it.response) {
                return it?.response?.data?.dataList ? it?.response?.data?.dataList[0] : [];
            } else {
                return it ? it : null;
            }
        });
        // if (item.limit == 1) {
        //   formartValue = formartValue[0] ? formartValue[0] : '';
        // }
    } else if (item.type == 'datepicker') {
        formartValue = val ? val.format(item.format ? item.format : 'YYYY-MM-DD') : null;
    } else if (item.type == 'daterange') {
        formartValue = val && Array.isArray(val) ? val.map((it) => (it ? moment(it).format(item.format ? item.format : 'YYYY-MM-DD') : null)) : [];
    }
    return formartValue;
}

const tabList = [
    {
        key: '1',
        tab: '线上产品',
    },
    {
        key: '2',
        tab: '下架产品',
    },
    {
        key: '3',
        tab: '被驳回',
    },
    {
        key: '4',
        tab: '待审核',
    },
    {
        key: '5',
        tab: '草稿箱',
    }
];

const list = [
];

export default () => {
    const [key, setkey] = useState("1"),
        [visible, setvisible] = useState(false),
        [dataSource, setSource] = useState({ list }),
        [selectedRowKeys, setSelectedRowKeys] = useState([]),
        rowSelection = {
            selectedRowKeys,
            preserveSelectedRowKeys: true,
            onChange: (keys) => setSelectedRowKeys(keys),
        },
        [iftype, ciftype] = useState({}),
        [fields, cf] = useState(defaultFields),
        [formRef] = Form.useForm(),
        [url, curl] = useState("/ngic-promote-product/umProduct/queryPage"),
        [params, cp] = useState({
            pageIndex: 1,
            pageSize: 5,
            status: 1,
        }),
        [indeterminate, setIndeterminate] = React.useState(false),
        [checkAll, setCheckAll] = React.useState(false);


    const { run, loading } = useRequest(doFetch, {
        manual: true,
        formatResult: (res) => res,
        onSuccess: (result, params) => {
            if (result.code == "0000") {
                setSource(result.data.page)
            }
        }
    })


    useEffect(() => {
        run({ url: url, params: params })
    }, [key, params, url]);


    useMemo(() => {
        let curpageid = dataSource.list.map(item => item.id);
        let containarr = selectedRowKeys.filter(it => curpageid.indexOf(it) != -1);
        if (selectedRowKeys.length == 0 || (containarr.length == curpageid.length && containarr.length > 0)) {
            setIndeterminate(false);
            if (selectedRowKeys.length == 0) {
                setCheckAll(false)
            }
            if (containarr.length == curpageid.length && containarr.length > 0) {
                setCheckAll(true)
            }
        } else if (containarr.length > 0) {
            setIndeterminate(true);
        } else if (containarr.length == 0) {
            setCheckAll(false);
            setIndeterminate(false);
        }
    }, [selectedRowKeys, dataSource])



    return (
        <div className={styles.mainsd}>
            <Card
                bordered={false}
                style={{ width: '100%', backgroundColor: "transparent" }}
                title="产品中心"
                extra={<a onClick={() => {
                    cf(fields => {
                        for (let i in fields) {
                            fields[i].value = i == "upload" ? [] : i == "productCaseDesc" ? `<p></p>` : null;
                        }
                        return { ...fields }
                    });
                    ciftype({
                        val: "add",
                        title: "新增"
                    })
                    setvisible(true)
                }}>添加产品</a>}
                tabBarExtraContent={<div className="rowcenter" style={{ width: 400 }}>
                    <Input size="default" placeholder="输入产品名称查询" prefix={<SearchOutlined />} style={{ flex: 1 }} onChange={(e) => {
                        let val = e.target.value;
                        cp({
                            ...params,
                            productName: val
                        })
                    }} />
                    <Checkbox
                        indeterminate={indeterminate}
                        style={{ marginLeft: 16 }}
                        checked={checkAll}
                        onChange={(e) => {
                            let curidarr = dataSource.list.map(it => it.id);
                            if (e.target.checked) {
                                setSelectedRowKeys(unique([...selectedRowKeys, ...curidarr]))
                            } else {
                                setSelectedRowKeys(selectedRowKeys.filter(it => curidarr.indexOf(it) == -1))
                            }
                            setCheckAll(e.target.checked);
                            setIndeterminate(false);
                        }}>全选</Checkbox>

                    {
                        key == "1" ?
                            <Popconfirm
                                title="确认下架该产品"
                                onConfirm={() => {
                                    if (selectedRowKeys.length == 0) {
                                        message.warn("请先选择需要下架的数据")
                                        return
                                    }
                                    doFetch({
                                        url: "/ngic-promote-product/umProduct/offByIdList",
                                        params: {
                                            idList: selectedRowKeys,
                                        }
                                    }).then(res => {
                                        if (res.code == "0000") {
                                            message.success("操作成功");
                                            run({ url: url, params: params })
                                        }
                                    })
                                }}
                                onCancel={() => {

                                }}
                                okText="下架"
                                cancelText="取消"
                            >
                                <Tooltip title="下架">
                                    <div className="actionbox">
                                        <img src={require("@/assets/down.png")} alt="" />
                                    </div>
                                </Tooltip>
                            </Popconfirm>
                            :
                            key == "2" ?
                                <Popconfirm
                                    title="确认上架该产品"
                                    onConfirm={() => {
                                        if (selectedRowKeys.length == 0) {
                                            message.warn("请先选择需要上架的数据")
                                            return
                                        }
                                        doFetch({
                                            url: "/ngic-promote-product/umProduct/onByIdList",
                                            params: {
                                                idList: selectedRowKeys,
                                            }
                                        }).then(res => {
                                            if (res.code == "0000") {
                                                message.success("操作成功");
                                                run({ url: url, params: params })
                                            }
                                        })
                                    }}
                                    onCancel={() => {

                                    }}
                                    okText="上架"
                                    cancelText="取消"
                                >
                                    <Tooltip title="上架">
                                        <div className="actionbox">
                                            <img src={require("@/assets/up.png")} alt="" style={{ width: 20 }} />
                                        </div>
                                    </Tooltip>
                                </Popconfirm>

                                : null
                    }
                    {
                        (key == "5" || key == "2") && <Popconfirm
                            title="确认删除该产品"
                            onConfirm={() => {
                                if (selectedRowKeys.length == 0) {
                                    message.warn("请先选择需要删除的数据")
                                    return
                                }
                                doFetch({
                                    url: key == "5" ? "/ngic-promote-product/omProductApply/deleteByIdList" :
                                        "/ngic-promote-product/umProduct/deleteOffByIdList", params: { idList: selectedRowKeys }
                                }).then(res => {
                                    if (res.code == "0000") {
                                        message.success("操作成功");
                                        run({ url: url, params: params })
                                    }
                                })
                            }}
                            onCancel={() => {

                            }}
                            okText="删除"
                            cancelText="取消"
                        >
                            <Tooltip title="删除">
                                <div className="actionbox" style={{ backgroundColor: "#ff98c5" }}>
                                    <img src={require("@/assets/delete.png")} alt="" />
                                </div>
                            </Tooltip>
                        </Popconfirm>
                    }



                </div>}
                tabList={tabList}
                activeTabKey={key}
                onTabChange={key => {
                    setSelectedRowKeys([]);
                    setkey(key);
                    if (key == "1") {
                        curl("/ngic-promote-product/umProduct/queryPage");
                        let newparams = {
                            ...params,
                            pageIndex: 1,
                            status: 1
                        }
                        cp(newparams)
                    } else if (key == "2") {
                        curl("/ngic-promote-product/umProduct/queryPage");
                        let newparams = {
                            ...params,
                            pageIndex: 1,
                            status: 2
                        }
                        cp(newparams)
                    } else if (key == "3") {
                        curl("/ngic-promote-product/omProductApply/queryNeedModifiedApplyPage");
                        let newparams = {
                            ...params,
                            pageIndex: 1,
                        }
                        delete newparams.status
                        cp(newparams)
                    } else if (key == "4") {
                        curl("/ngic-promote-product/omProductApply/queryWaitAuditPage");
                        let newparams = {
                            ...params,
                            pageIndex: 1,
                        }
                        delete newparams.status
                        cp(newparams)
                    } else {
                        curl("/ngic-promote-product/omProductApply/queryDraftPage");
                        let newparams = {
                            ...params,
                            pageIndex: 1,
                        }
                        delete newparams.status
                        cp(newparams)
                    }
                }}
            >
                <div style={{ backgroundColor: "#fff", margin: -20 }}>
                    <ProList
                        metas={{
                            title: {
                                dataIndex: "productName"
                            },
                            description: {
                                render: (text, record) => {
                                    return <div className="rowcenter" style={{ justifyContent: "flex-start", fontSize: 14 }}>
                                        {
                                            (key == "1" || key == "2") && <>
                                                <EyeFilled style={{ fontSize: 18 }} />
                                                <span className="oneline" style={{ marginRight: 6, marginLeft: 6, width: 36 }}>{record.viewNum || 0}</span>
                                            </>
                                        }

                                        <ClockCircleFilled style={{ fontSize: 15 }} />
                                        <span className="oneline" style={{ marginRight: 6, marginLeft: 6 }}>{record.updateTime}</span>
                                    </div>;
                                },
                            },
                            avatar: {
                                dataIndex: "productImageUrlList",
                                key: "productImageUrlList",
                                render: (text, record) => {
                                    return <Avatar src={record?.productImageUrlList[0]?.url} style={{ boxShadow: "0 0 2px #aaa" }} size="large"></Avatar>;
                                },
                            },
                            actions: {
                                render: (text, record) => {
                                    return [
                                        key == "1" ?
                                            <Popconfirm
                                                title="确认下架该产品"
                                                onConfirm={() => {
                                                    doFetch({
                                                        url: "/ngic-promote-product/umProduct/offByIdList",
                                                        params: {
                                                            idList: [record.id],
                                                        }
                                                    }).then(res => {
                                                        if (res.code == "0000") {
                                                            message.success("操作成功");
                                                            run({ url: url, params: params })
                                                        }
                                                    })
                                                }}
                                                onCancel={() => {

                                                }}
                                                okText="下架"
                                                cancelText="取消"
                                            >
                                                <Tooltip title="下架">
                                                    <img src={require("@/assets/downs.png")} style={{ cursor: "pointer" }} />
                                                </Tooltip>
                                            </Popconfirm> :
                                            key == "2" ?
                                                <Popconfirm
                                                    title="确认上架该产品"
                                                    onConfirm={() => {
                                                        doFetch({
                                                            url: "/ngic-promote-product/umProduct/onByIdList",
                                                            params: {
                                                                idList: [record.id],
                                                            }
                                                        }).then(res => {
                                                            if (res.code == "0000") {
                                                                message.success("操作成功");
                                                                run({ url: url, params: params })
                                                            }
                                                        })
                                                    }}
                                                    onCancel={() => {

                                                    }}
                                                    okText="上架"
                                                    cancelText="取消"
                                                >
                                                    <Tooltip title="上架">
                                                        <img src={require("@/assets/ups.png")} style={{ cursor: "pointer" }} />
                                                    </Tooltip>
                                                </Popconfirm>
                                                : null
                                        ,
                                        <Tooltip title="编辑">
                                            <img src={require("@/assets/edits.png")} style={{ cursor: "pointer" }} onClick={() => {
                                                cf(fields => {
                                                    for (let i in fields) {
                                                        fields[i].value = record[i];
                                                        if(i=="priceList"){
                                                           fields[i].dataSource = record[i]
                                                        }
                                                    }
                                                    
                                                    return { ...fields }
                                                });
                                                ciftype({
                                                    val: "edit",
                                                    id: record.id,
                                                    productId: record.productId,
                                                    title: "修改"
                                                })
                                                setvisible(true);


                                            }} />
                                        </Tooltip>,
                                        (key == "5" || key == "2") &&
                                        <Popconfirm
                                            title="确认删除该产品"
                                            onConfirm={() => {
                                                doFetch({
                                                    url: key == "5" ? "/ngic-promote-product/omProductApply/deleteByIdList" :
                                                        "/ngic-promote-product/umProduct/deleteOffByIdList", params: { idList: [record.id] }
                                                }).then(res => {
                                                    if (res.code == "0000") {
                                                        message.success("操作成功");
                                                        run({ url: url, params: params })
                                                    }
                                                })

                                            }}
                                            onCancel={() => {

                                            }}
                                            okText="删除"
                                            cancelText="取消"
                                        >
                                            <Tooltip title="删除">
                                                <img src={require("@/assets/deletes.png")} style={{ cursor: "pointer" }} />
                                            </Tooltip>
                                        </Popconfirm>
                                    ];
                                },
                            },
                        }}
                        rowKey="id"
                        rowSelection={rowSelection}
                        dataSource={dataSource?.list || []}
                        pagination={{
                            defaultPageSize: params.pageSize,
                            showSizeChanger: true,
                            size: "small",
                            total: dataSource.total || 1,
                            onChange: (pageIndex, pageSize) => {
                                cp({
                                    ...params,
                                    pageIndex,
                                    pageSize
                                })
                            }

                        }}
                        style={{}}
                    />
                </div>

            </Card>


            <DragModal
                title={iftype.title}
                visible={visible}
                width={1200}
                onCancel={() => {
                    setvisible(false);
                }}
                footer={[
                    <Button onClick={() => {
                        setvisible(false)
                    }}>取消</Button>,
                    (!(key == "1" || key == "2" || key == "3") || iftype.val == "add") &&
                    <Button type="primary" ghost onClick={() => {
                        formRef.validateFields()
                            .then((values) => {
                                let newvalue = { ...values };
                                for (let i in defaultFields) {
                                    newvalue[i] = formartData(defaultFields[i], values[i]);
                                }
                                doFetch({
                                    url: "/ngic-promote-product/omProductApply/saveDraft",
                                    params: { ...newvalue, id: iftype.val == "add" ? "" : iftype.id }
                                }).then(res => {
                                    if (res.code == "0000") {
                                        message.success("操作成功");
                                        setvisible(false)
                                        run({ url: url, params: params })
                                    }
                                })
                            })
                    }}>存为草稿</Button>,
                    <Button type="primary" onClick={() => {
                        formRef.validateFields()
                            .then((values) => {
                                let newvalue = { ...values };
                                for (let i in defaultFields) {
                                    newvalue[i] = formartData(defaultFields[i], values[i]);
                                }
                                for (let i in newvalue) {
                                    if (i == "priceList") {
                                        newvalue[i] = newvalue[i]?.map(it => {
                                            return {
                                                fromOrderQuantity: it.fromOrderQuantity,
                                                unitPrice: it.unitPrice,
                                                isDiscuss: it.isDiscuss
                                            }
                                        })
                                    }
                                    if (i == "paramList") {
                                        newvalue[i] = newvalue[i]?.map(it => {
                                            return {
                                                paramName: it.paramName,
                                                paramValue: it.paramValue
                                            }
                                        })
                                    }
                                }
                                let upadteurl = "/ngic-promote-product/omProductApply/saveApply";
                                let productId = (key == "1" || key == "2" ) && iftype.val != "add" ? {productId:iftype.id}:{};
                                let rowId = (key == "1" || key == "2" ) && iftype.val != "add" ? {}:{id:iftype.id};
                                doFetch({
                                    url: iftype.val == "add" ? "/ngic-promote-product/omProductApply/saveApply" : upadteurl,
                                    params: { ...newvalue, ...rowId,...productId }
                                }).then(res => {
                                    if (res.code == "0000") {
                                        message.success("操作成功");
                                        setvisible(false)
                                        run({ url: url, params: params })
                                    }
                                })
                            })
                    }}>提交审核</Button>
                ]}
            >
                <InitForm
                    formRef={formRef}
                    fields={fields}
                    onChange={(value, allValues) => {

                    }}
                    actions={() => null}
                ></InitForm>
            </DragModal>


        </div>
    )


}